package com.gdth.bank.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.json.JSONException;
import org.json.JSONObject;

import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.bean.DownloadBean;
import com.gdth.bank.model.DownloadModel;
import com.gdth.bank.presenter.WebViewPresenter;
import com.gdth.bank.utils.AppUtil;
import com.gdth.bank.utils.Callback;
import com.gdth.bank.utils.LogUtils;
import com.gdth.bank.utils.WebViewUtil;
import com.gdth.bank.view.WebViewView;
import com.gdth.bank.widget.BankWebViewClient;
import com.gdth.bank.widget.image.Bimp;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseActivity;
import com.gdth.database.bean.TAppFjxxb;
import com.gdth.database.bean.TAppYh;
import com.gdth.http.method.EngDNS;
import com.gdth.http.method.httpsUtils;
import com.gdth.resource.Constant;
import com.gdth.utils.ContentUriUtil;
import com.gdth.utils.ToolUtil;
import com.gdth.utils.UUIDUtil;
import com.gdth.utils.webViewUtils;
import com.gdth.widget.dialog.BaseToast;
import com.gdth.widget.webview.BaseWebChromeClient;
import com.gdth.widget.webview.BaseWebChromeClient.WebChromeClientListener;
import com.gdth.widget.webview.WebViewUnit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.TextView;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WebViewActivity extends BaseActivity implements WebViewView,Callback{
	@ViewInject(id=R.id.header_label_title) TextView txt_header_title;
	@ViewInject(id=R.id.header_btn_left, click="returnClick") TextView txt_header_left;
	@ViewInject(id=R.id.header_btn_right) TextView txt_header_right;
	List<TAppFjxxb> scfjList;
	String path;
	protected static final int REQUEST_CODE_PICK_IMAGE = 6666;
	protected static final int REQUEST_CODE_IMAGE_CAPTURE = 8888;
	protected static final int REQUEST_CODE_CANCEL = 9999;

	private WebView mWebView;
	private BaseWebChromeClient mBaseWebChromeClient ;
	final Activity activity = this; 

	WebViewPresenter mPresenter;

	private Handler mHandler = new Handler();

	private boolean isClose = false;

	private int steps = 0;
	private int state = 0;
	private String neturl;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().requestFeature(Window.FEATURE_PROGRESS); 
		setContentView(R.layout.activity_webview);

		initView();
	}



	private void initView(){
		txt_header_right.setVisibility(View.GONE);
		Intent intent = this.getIntent();
		String path = intent.getStringExtra("path");
		String name = intent.getStringExtra("name");
		if (name != null) 
			txt_header_title.setText(name);

		mWebView = (WebView) findViewById(R.id.webView);
		//		初始化WebSettings
		WebViewUnit.getWebSettings(this, mWebView);

		mBaseWebChromeClient = new BaseWebChromeClient(this);
		mBaseWebChromeClient.setWebChromeClientListener(mWebChromeClientListener);
		mWebView.setWebChromeClient(mBaseWebChromeClient);
		mWebView.setWebViewClient(new BankWebViewClient(this, this));

		//	    注册供JavaScript调用的事件
		mWebView.addJavascriptInterface(this, "webview");

		//	    加载页面
		//		mWebView.loadUrl("file:///android_asset/jsdroid.html");
		//	    mWebView.loadUrl("http://192.168.1.26:8080/yxrcb-app/bank/zdyx/zdyx!edit.do");
		//	    mWebView.loadUrl("http://192.168.1.26:8080/yxrcb-app/" + path);
		//	    mWebView.loadUrl(BankApplication.getServiceUrl() + "bank/zdyx/zdyx!edit.do");
		 Map<String, String> extraHeaders = new HashMap<String, String>();
	     extraHeaders.put("attestation", webViewUtils.getHeadParam());
	     mWebView.getSettings().setUserAgentString("okhttp viewAction");
		 mWebView.loadUrl((BankApplication.mInstance.url + path) , extraHeaders);

		mPresenter = new WebViewPresenter(this);
	}
	private Handler handler=new Handler();
	
	@Override
	public void onBackPressed() {
		returnClick(null);
	}
	
	@Override
	public void onDestroy() {
		WebViewUnit.clearWebViewCache(this);
		//		removeView(mWebView);  
		//		mWebView.destroy();
		//		WebView cookies清理
		CookieSyncManager.createInstance(this);   
		CookieSyncManager.getInstance().startSync();   
		CookieManager.getInstance().removeSessionCookie();
		//		清理cache和历史记录:
		mWebView.clearCache(true);   
		mWebView.clearHistory();  
		super.onDestroy();

	}

	public void returnClick(View arg0) {
		String url = mWebView.getUrl();
		if(url.equals(WebViewUtil.ERROR_URL)){
			finish();
		}else if(mWebView.canGoBack() && isClose) {
			if(state == 1 && !TextUtils.isEmpty(neturl)) {
				if(mWebView.canGoBackOrForward(steps+1)){
					mWebView.goBackOrForward(steps+1);
					//mWebView.loadUrl(BankApplication.mInstance.url + neturl);
				}
			}else if(state == 2 && !TextUtils.isEmpty(neturl)){
				backForwardHiml(BankApplication.mInstance.url + neturl);
				//mWebView.reload();
			}else if(state == 3) {
				finish();
			}else {
				mWebView.goBack();
			}
		}else if (mWebView.canGoBack()) {
			mWebView.goBack();
		} else {
			finish();
		}
	}
	//--------上传图片----------
	//url请求,含文件上传,新接口
	@JavascriptInterface
	public void initSCFJList() {
		scfjList = new ArrayList<TAppFjxxb>();
	}
	@JavascriptInterface
	public void uploadFile(final String glbs,final int gnmk,final String callback) throws JSONException{
		final JSONObject result = new JSONObject();
		try{
			if(scfjList!=null){
				for (TAppFjxxb mTAppFjxxb : scfjList) {
					if(mTAppFjxxb!=null){
						String[] ids = glbs.split(",");
						for (String id: ids) {
							DownloadBean bean = new DownloadBean();
							bean.setName(mTAppFjxxb.getWjmc());
							bean.setWjlx(mTAppFjxxb.getWjlx());
							bean.setUuid(UUIDUtil.getUUID());
							bean.setWybs(id);
							bean.setLocalPath(mTAppFjxxb.getAppdz());
							bean.setSqrsfz(mTAppFjxxb.getSfz());
							bean.setScms(0);
							bean.setCjsj(new Date());
							bean.setGnmk(gnmk);
							bean.setFjlx(5);
							bean.setZdlx(1);
							DownloadModel.getInstance().upload(bean);
						}
					}
				}
			}
			result.put("result", "success");
			result.put("msg", "保存成功");
		}catch(Exception e){
			result.put("result", "error");
			result.put("msg", "保存失败,"+e.getMessage());
		}
		mHandler.post(new Runnable() {
			public void run() {
				mWebView.loadUrl("javascript:"+callback+"('"+result.toString()+"')");
			}
		});
	}
	@JavascriptInterface
	public void uploadFileUrl(String content,final String glbs,final int gnmk,String url,String callback){
		if(scfjList!=null){
			for (TAppFjxxb mTAppFjxxb : scfjList) {
				if(mTAppFjxxb!=null){
					String[] ids = glbs.split(",");
					for(String id: ids) {
						DownloadBean bean = new DownloadBean();
						bean.setName(mTAppFjxxb.getWjmc());
						bean.setWjlx(mTAppFjxxb.getWjlx());
						bean.setUuid(UUIDUtil.getUUID());
						bean.setWybs(id);
						bean.setLocalPath(mTAppFjxxb.getAppdz());
						bean.setSqrsfz(mTAppFjxxb.getSfz());
						bean.setScms(0);
						bean.setCjsj(new Date());
						bean.setGnmk(gnmk);
						bean.setFjlx(5);
						bean.setZdlx(1);
						DownloadModel.getInstance().upload(bean);
					}

				}
			}
		}
		mPresenter.getData(content, url,callback);
	}
	@JavascriptInterface
	public void deleteFile(int i) {
		scfjList.set(i, null);
	}
	private void addFile(Intent intent){
		if(intent!=null){
			path = ContentUriUtil.getPath(activity, intent.getData());
		}
		if(path!=null){
			String wjmc = path.substring(path.lastIndexOf("/")+1);
			String wjlx = wjmc.substring(wjmc.lastIndexOf(".")+1).toUpperCase();
			if(!wjlx.equals("BMP")&&!wjlx.equals("PNG")&&!wjlx.equals("GIF")&&!wjlx.equals("JPG")&&!wjlx.equals("JPEG")){
				//仅支持jpg/jpeg/png/gif/bmp格式的照片上传
				return;
			}
			for(TAppFjxxb bean:scfjList){
				//已选择的文件不在添加
				if(bean!=null&&bean.getAppdz().equals(path)){
					return;
				}
			}
			scfjList.add(createFJ());
		}
	}
	private TAppFjxxb createFJ() {
		if(path==null||path.trim().length()==0){
			return null;
		}
		String wjmc = path.substring(path.lastIndexOf("/")+1);
		String wjlx = wjmc.substring(wjmc.lastIndexOf(".")+1);
		TAppYh user = BankApplication.mInstance.getCurrentUser();
		TAppFjxxb tAppFjxxb = new TAppFjxxb();
		tAppFjxxb.setAppdz(path);
		tAppFjxxb.setSfz(user.getSfz());
		tAppFjxxb.setUuid(UUIDUtil.getUUID());
		tAppFjxxb.setWjlx(wjlx);
		tAppFjxxb.setWjmc(wjmc);
		return tAppFjxxb;
	}
	public void showUploadOptions() {  
		path = null;
		String url = mWebView.getUrl();
		String status=Environment.getExternalStorageState(); 
		if(status.equals(Environment.MEDIA_MOUNTED)) {
			String uploadtype = null;
			if(url.indexOf("uploadtype=")>0){
				url = url.substring(url.indexOf("uploadtype=")+"uploadtype=".length());
				if(url.indexOf("_u")>0){
					uploadtype = url.substring(0,url.indexOf("_u"));
				}
			}
			if(uploadtype==null){
				BaseToast.getInstance().ShowSystemToast(activity, "错误的uploadtype参数类型"); 
				cancelUpload();
			}else{
				if(uploadtype.equals("1")){
					imageCapture();//拍照
				}else if(uploadtype.equals("2")){
					pickImage();//本地上传
				}else if(uploadtype.equals("3")){
					showDialog();//拍照，本地上传对话框
				}else{
					BaseToast.getInstance().ShowSystemToast(activity, "错误的uploadtype参数类型"); 
					cancelUpload();
				}
			}
		}  else { 
			BaseToast.getInstance().ShowSystemToast(activity, "没有储存卡"); 
			cancelUpload();
		} 
	}  
	public void showDialog(){
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);  
		alertDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface arg0) {
				cancelUpload();
			}
		});
		alertDialog.setTitle("请选择文件方式");  
		alertDialog.setItems(new String[] { "拍照上传", "本地上传"}, new DialogInterface.OnClickListener() {  
			@Override  
			public void onClick(DialogInterface dialog, int which) {  
				if (which == 0) {  
					imageCapture();
				} else {  
					pickImage();
				}  
			}  
		});  
		alertDialog.show();  
	}
	public void cancelUpload(){
		if (mBaseWebChromeClient.mUploadMessage != null) {  
			mBaseWebChromeClient.mUploadMessage.onReceiveValue(null);  
			mBaseWebChromeClient.mUploadMessage = null;  
		}  
		if (mBaseWebChromeClient.uploadMessage != null) {  
			mBaseWebChromeClient.uploadMessage.onReceiveValue(null);  
			mBaseWebChromeClient.uploadMessage = null;  
		}  
	}
	public void pickImage() {  
		Intent i = new Intent(Intent.ACTION_GET_CONTENT);
		i.addCategory(Intent.CATEGORY_OPENABLE);
		i.setType("image/*");
		startActivityForResult(Intent.createChooser(i, "File Browser"), REQUEST_CODE_PICK_IMAGE);
	} 
	
	public void imageCapture(){
    	String uuid = UUIDUtil.getUUID();
		String name = uuid + ".jpg";
		
		path = ToolUtil.getFileFullPath(ToolUtil.getFilePath(name));
		File file = new File(path);
		Uri imageUri = null;
		if (Build.VERSION.SDK_INT >= 24) {
			imageUri =  FileProvider.getUriForFile(activity, "com.jph.takephoto.fileprovider", file);//通过FileProvider创建一个content类型的Uri
		} else {
			imageUri = Uri.fromFile(file);
		}
    	Intent i = new Intent();
    	i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
    	i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
    	i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
    	i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
    	startActivityForResult(i, REQUEST_CODE_IMAGE_CAPTURE);
    }

	@SuppressLint("NewApi")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent)
	{
		super.onActivityResult(requestCode, resultCode, intent);
		if (requestCode == REQUEST_CODE_PICK_IMAGE){
			if (mBaseWebChromeClient.mUploadMessage != null ){
				Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
				if(intent!=null){
					addFile(intent);
				}
				mBaseWebChromeClient.mUploadMessage.onReceiveValue(result);
				mBaseWebChromeClient.mUploadMessage = null;
			}
			if (mBaseWebChromeClient.uploadMessage != null){
				Uri[] result = WebChromeClient.FileChooserParams.parseResult(resultCode, intent);
				if(intent!=null){
					addFile(intent);
				}
				mBaseWebChromeClient.uploadMessage.onReceiveValue(result);
				mBaseWebChromeClient.uploadMessage = null;
			}
		}
		if (requestCode == REQUEST_CODE_IMAGE_CAPTURE){
			if(resultCode == MainActivity.RESULT_OK ){
				try {
					Bimp.setCompressor(ToolUtil.getFileFullPath(path),null);
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (mBaseWebChromeClient.mUploadMessage != null ){
					String sourcePath = path;
					Uri result = null;
					if(sourcePath!=null){
						addFile(null);
						result = Uri.fromFile(new File(sourcePath));
					}
					mBaseWebChromeClient.mUploadMessage.onReceiveValue(result);
					mBaseWebChromeClient.mUploadMessage = null;
				}
				if (mBaseWebChromeClient.uploadMessage != null){
					String sourcePath = path;
					Uri[] result = null;
					if(sourcePath!=null){
						addFile(null);
						result = new Uri[]{Uri.fromFile(new File(sourcePath))};
					}
					mBaseWebChromeClient.uploadMessage.onReceiveValue(result);
					mBaseWebChromeClient.uploadMessage = null;
				}
			}else{
				mBaseWebChromeClient.uploadMessage.onReceiveValue(null);
				mBaseWebChromeClient.uploadMessage = null;
			}
		}
		if(requestCode == 0){
			String val = intent.getStringExtra("result");
			Bundle bundle = intent.getExtras();  
			Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
			String call = "javascript:alertMessage(\"" + val + "\", \"" + bitmap +"\")";
			mWebView.loadUrl(call);
		}
	}
	//----------上传图片END------


	@Override
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub

	}

	@Override
	public void hideProgressDialog() {
		// TODO Auto-generated method stub

	}

	@Override
	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		BaseToast.getInstance().ShowSystemToast(this, msg);

	}

	@Override
	public void updateViewForTest(String val) {
		// TODO Auto-generated method stub

		mHandler.post(new Runnable() {
			public void run() {
				mWebView.loadUrl("javascript:test(1)");
			}
		});
	}

	@Override
	public void returnBm(String val) {
		// TODO 返回部门
		callJavaScript("bm", val);
	}

	@Override
	public void returnCanshu(String json, String type) {
		// TODO 返回参数
		callJavaScript(type, json);
	}

	private WebChromeClientListener mWebChromeClientListener = new WebChromeClientListener() {

		@Override
		public void onReceivedTitle(String title) {
			// TODO Auto-generated method stub
			txt_header_title.setText(title);
		}

	};


	/*********************************JavascriptInterface***********************************/
	//这里定义页面js调用的方法，必须加注解
	//返回方法默认return + 这里的方法名
	//这里采用mvp模式调用一个http接口
	@JavascriptInterface
	public void getAllBm(){
		mPresenter.getAllBm();
	}

	@JavascriptInterface
	public void getYh(){
		String val = BankApplication.mInstance.getCurrentUserForJson();
		callJavaScript("yh", val);
	}
	@JavascriptInterface
	public void goBack(){
		mHandler.post(new Runnable() {
			public void run() {
				String url = mWebView.getUrl();
				if(url.equals(WebViewUtil.ERROR_URL)){
					finish();
				}else if (mWebView.canGoBack()) {
					mWebView.goBack();
				} else {
					finish();
				}
			}
		});
	}
	@JavascriptInterface
	public void backMenu(){
		mHandler.post(new Runnable() {
			public void run() {
				finish();
			}
		});
	}
	@JavascriptInterface
	public void getZjlx(){
		String json = getCanshuByType(AppUtil.SHARE_DATA_ZJLX_ZDYX);
		if (json == null) {
			getCanshuByType(AppUtil.SHARE_DATA_ZJLX_ZDYX);
		} else 
			callJavaScript(AppUtil.SHARE_DATA_ZJLX_ZDYX, json);
	}
	@JavascriptInterface
	public void getKhlb(){
		String json = getAllKhlbByType(AppUtil.SHARE_DATA_KHLB);
		if (json == null) {
			getAllKhlbByType(AppUtil.SHARE_DATA_KHLB);
		} else 
			callJavaScript(AppUtil.SHARE_DATA_KHLB, json);
	}
	@JavascriptInterface
	public void getZdyx(){
		String json = getAllZdyxByType(AppUtil.SHARE_DATA_ZDYX);
		if (json == null) {
			getAllZdyxByType(AppUtil.SHARE_DATA_ZDYX);
		} else 
			callJavaScript(AppUtil.SHARE_DATA_ZDYX, json);
	}
	@JavascriptInterface
	public void getAllYxzl(){
		String json = getCanshuByType(AppUtil.SHARE_DATA_YXZL);

		callJavaScript(AppUtil.SHARE_DATA_YXZL, json);
	}

	private String getCanshuByType(String type) {
		String val = AppUtil.getCanshuForJson(this, type);
		return val;
	}

	private String getAllKhlbByType(String type){
		String val = AppUtil.getAllkhlbJson(this,type);
		return val;
	}
	private String getAllZdyxByType(String type){
		String val = AppUtil.getAllzdyxJson(this,type);
		return val;
	}
	@JavascriptInterface
	public void saveZdyxsb(String content) {
		getData(content, 1);
	}

	@JavascriptInterface
	public void findZdys(String content) {
		getData(content, 2);
	}

	@JavascriptInterface
	public void updataSBBL(String content) {
		getData(content, 3);
	}

	@JavascriptInterface
	public void pageZdyxsbList(String content) {
		getData(content, 4);
	}

	/*****************存款维护**************/
	@JavascriptInterface
	public void pageCkwhList(String content) {
		getData(content, 5);
	}

	@JavascriptInterface
	public void findCkwh(String content) {
		getData(content, 6);
	}

	/*****************存款拓展**************/
	@JavascriptInterface
	public void pageCktzList(String content) {
		getData(content, 7);
	}

	@JavascriptInterface
	public void findCktz(String content) {
		getData(content, 8);
	}

	@JavascriptInterface
	public void pageDkghList(String content) {
		getData(content, 9);
	}

	@JavascriptInterface
	public void findDkgh(String content) {
		getData(content, 10);
	}
	@JavascriptInterface
	public void pageDkghAcList(String content) {
		getData(content, 11);
	}
	@JavascriptInterface
	public void pageDkbsList(String content) {
		getData(content, 12);
	}
	@JavascriptInterface
	public void findDkbsdj(String content) {
		getData(content, 13);
	}
	@JavascriptInterface
	public void pageDkbsdjAcList(String content) {
		getData(content, 14);
	}
	/*****************存款考核计价汇总数据**************/
	@JavascriptInterface
	public void getCkkhjjhz(String content) {
		getData(content, 15);
	} 
	@JavascriptInterface
	public void getJjJsHz(String content) {
		getData(content, 16);
	} 
	@JavascriptInterface
	public void getJxgzhzmx(String content) {
		getData(content, 17);
	} 
	@JavascriptInterface
	public void getDateByZH(String content) {
		getData(content, 18);
	} 
	/*****************员工绩效**************/
	@JavascriptInterface
	public void listBmByYhZh(String content) {
		getData(content, 19);
	} 
	@JavascriptInterface
	public void listYgByJg(String content) {
		getData(content, 20);
	} 
	@JavascriptInterface
	public void getYwljjhz(String content) {
		getData(content, 21);
	} 
	@JavascriptInterface
	public void listYwljjjs(String content) {
		getData(content, 22);
	} 
	@JavascriptInterface
	public void getTjDate(String content) {
		getData(content, 23);
	} 
	@JavascriptInterface
	public void pageLxList(String content) {
		getData(content, 24);
	} 
	@JavascriptInterface
	public void getDkyxjjhz(String content) {
		getData(content, 25);
	} 
	@JavascriptInterface
	public void listDkyxjjjs(String content) {
		getData(content, 26);
	} 
	@JavascriptInterface
	public void getDkghjjhz(String content) {
		getData(content, 27);
	} 
	@JavascriptInterface
	public void getDkghJjJsHz(String content) {
		getData(content, 28);
	} 
	@JavascriptInterface
	public void getDkbsndkh(String content) {
		getData(content, 29);
	} 
	@JavascriptInterface
	public void listDkbsjjmx(String content) {
		getData(content, 30);
	} 
	@JavascriptInterface
	public void getDkbsyqkhhz(String content) {
		getData(content, 31);
	} 
	@JavascriptInterface
	public void listDkbsyqkhhzjjs(String content) {
		getData(content, 32);
	} 
	@JavascriptInterface
	public void getDkbsyqdfhz(String content) {
		getData(content, 33);
	} 
	@JavascriptInterface
	public void listDkbsyqdfMx(String content) {
		getData(content, 34);
	} 
	@JavascriptInterface
	public void getGljxgzjjhz(String content) {
		getData(content, 35);
	} 
	@JavascriptInterface
	public void getBsyqdk(String content) {
		getData(content, 36);
	} 
	@JavascriptInterface
	public void getYqdkbsnddqjs(String content) {
		getData(content, 37);
	} 
	@JavascriptInterface
	public void getYqdkbsnddqjsjs(String content) {
		getData(content, 38);
	} 
	@JavascriptInterface
	public void getGljxgzjjhzMx(String content) {
		getData(content, 39);
	}
	@JavascriptInterface
	public void dzyhjjkhgzhz(String content) {
		getData(content, 40);
	} 
	@JavascriptInterface
	public void listDzyhjjjsMx(String content) {
		getData(content, 41);
	}
	@JavascriptInterface
	public void gljxgzjjhzMx(String content) {
		getData(content, 42);
	}
	@JavascriptInterface
	public void khkkmx(String content) {
		getData(content, 43);
	}
	@JavascriptInterface
	public void yfjxgzmx(String content) {
		getData(content, 44);
	}
	@JavascriptInterface
	public void sgjjmx(String content) {
		getData(content, 45);
	}
	@JavascriptInterface
	public void saveHdtz(String content) {
		getData(content, 46);
	}
	@JavascriptInterface
	public void hdtzList(String content) {
		getData(content, 47);
	}
	@JavascriptInterface
	public void saveQxtz(String content) {
		getData(content, 48);
	}
	@JavascriptInterface
	public void getHdtz(String content) {
		getData(content, 49);
	}
	@JavascriptInterface
	public void getHdmc(String content) {
		getData(content, 50);
	}
	@JavascriptInterface
	public void saveSbkcj(String content) {
		getData(content, 51);
	}
	@JavascriptInterface
	public void pageSbkcjxxList(String content) {
		getData(content, 52);
	}
	public void getData(String content, int type) {
		mPresenter.getData(content, type);
	}

	//url请求,新接口
	@JavascriptInterface
	public void loadUrl(String content,String url,String callback){
		mPresenter.getData(content, url,callback);
	}

	/**
	 * 返回上层界面逻辑
	 * @param steps	 关闭页面 为负数   数值为返回次数
	 * @param state	1.跳转    2.根据url 关闭url所在栈之上的栈   3.直接关闭
	 * @param url	跳转路径
	 */
	@JavascriptInterface
	public void canGoBackhtml(int steps, int state, String url) {
		this.steps = steps;
		this.state = state;
		this.neturl = url;
		isClose = true;
	}

	/**
	 *  根据url 关闭url所在栈之上的栈
	 * @param url
	 */
	private void backForwardHiml(String url) {
		WebBackForwardList webBackForwardList = mWebView.copyBackForwardList();
		int index = -1;
		while (mWebView.canGoBackOrForward(index)) {
			int currentIndex = webBackForwardList.getCurrentIndex();
			String lastUrl = webBackForwardList.getItemAtIndex(index + currentIndex).getUrl();
			if(!lastUrl.equals(WebViewUtil.ERROR_URL)&&!url.equals(lastUrl)) {
				mWebView.goBackOrForward(index);
				url = lastUrl;
				break;
			}
			index--;
		}
	}
	
	@JavascriptInterface
	public void getUrl(String url,String callback){
//		if(!url.contains("attestation=")) {
//			url = webViewUtils.NewUrl(url);
//		}
		geturl(url, callback);
	}
	
	   private OkHttpClient getOkHttpClient(){

	    	OkHttpClient client = new OkHttpClient.Builder()
	    		.connectTimeout(1000, TimeUnit.SECONDS)
//	    		.connectTimeout(1000, TimeUnit.MINUTES)
			    .readTimeout(1000, TimeUnit.MINUTES)
			    .writeTimeout(3000, TimeUnit.MINUTES)
				.dns(new EngDNS())
	    		.sslSocketFactory(httpsUtils.getSSLSocketFactory())
	    		.hostnameVerifier(httpsUtils.getHostnameVerifier())
	    		.build();
	    	
	    	return client;
	    }
	   
	   public void geturl(String url ,final String callback) {
			OkHttpClient okHttpClient= getOkHttpClient();
			try{
				 Request request=new Request.Builder()
					        .get()
					        .url( Constant.image_url_param + url)
					        .addHeader("attestation",   webViewUtils.getHeadParam())
					        .build();
					  Call call=okHttpClient.newCall(request);
					  call.enqueue(new okhttp3.Callback() {
									
						@Override
						public void onFailure(Call arg0, IOException arg1) {
							// TODO Auto-generated method stub
							LogUtils.i("=======", arg1.getMessage());
						}

						@Override
						public void onResponse(Call arg0, Response arg1) throws IOException {
							// TODO Auto-generated method stub
							if(arg1.isSuccessful()) {
								final String content = arg1.body().string();
								runOnUiThread(new Runnable() {
									
									@Override
									public void run() {
										String msg = "";
										try{
											msg = content.replaceAll("\r|\n", "!-n").replaceAll("'", "!-s").replaceAll("\"", "!-d").replaceAll("(!-n)+", "!-n");
											//msg = Base64.encodeToString(content.getBytes("Unicode"), Base64.DEFAULT);
										}catch(Exception e){
											LogUtils.i("=======", e.getMessage());
										}
										returnData(msg,callback);
									}
								});
							}
						}
					});
			}catch(Exception e){
				LogUtils.i("=======", e.getMessage());
			}
			 
		} 

	   
	   public String toBinary(String str){
		     
		      char[] strChar=str.toCharArray();
		      String result="";
		      for(int i=0;i<strChar.length;i++){
		          result +=Integer.toBinaryString(strChar[i])+ " ";
		      }
		     // System.out.println(result);
		      return result;
		  }
	   
	   /**
	     * 将字节数组转换为字符串
	     * 一个字节会形成两个字符，最终长度是原始数据的2倍
	     * @param data
	     * @return
	     */
	    public static String toHex(byte[] data){
	        String ret = null;

	        //TODO 将字节数组转换为字符串
	        if (data != null && data.length>0) {
	            StringBuilder sb = new StringBuilder();
	            for (byte b: data){
	                //分别获取高四位，低四位的内容，将两个数值，转为字符
	                int h = (b>>4)&0x0f;
	                int l = b&0x0f;
	                char ch ,cl;
	                if( h > 9 ){
	                    ch = (char) ('A'+(h-10));
	                }else{  //0--9
	                    ch = (char) ('0'+h);
	                }

	                if(l>9){
	                    cl = (char) ('A'+(l-10));
	                }else{  //0--9
	                    cl = (char) ('0'+l);
	                }


	                    sb.append(ch).append(cl);
	                }
	                  ret = sb.toString();
	            }

	        return ret;
	    }
	/*****************************************返回方法默认方法名**************************************************/
	/**
	 * url请求,新接口
	 */
	public void returnData(String result, String callback) {
		mWebView.loadUrl("javascript:"+callback+"('"+result+"')");
	}
	/**
	 * 然后html页面数据
	 * 返回方法默认return + 这里的方法名
	 */
	public void returnData(String result, int type) {
		switch(type) {
		case 1 :
			mWebView.loadUrl("javascript:returnSaveZdyxsb('"+result+"')");
			break;
		case 2 :
			mWebView.loadUrl("javascript:returnFindZdys('"+result+"')");
			break;
		case 3 :
			mWebView.loadUrl("javascript:returnUpdataSBBL('"+result+"')");
			break;
		case 4 :
			mWebView.loadUrl("javascript:returnPageZdyxsbList('"+result+"')");
			break;
		case 5 :
			mWebView.loadUrl("javascript:returnPageCkwhList('"+result+"')");
			break;
		case 6 :
			mWebView.loadUrl("javascript:returnFindCkwh('"+result+"')");
			break;
		case 7 :
			mWebView.loadUrl("javascript:returnPageCktzList('"+result+"')");
			break;
		case 8 :
			mWebView.loadUrl("javascript:returnFindCktz('"+result+"')");
			break;
		case 9 :
			mWebView.loadUrl("javascript:returnPageDkghList('"+result+"')");
			break;
		case 10 :
			mWebView.loadUrl("javascript:returnFindDkgh('"+result+"')");
			break;
		case 11 :
			mWebView.loadUrl("javascript:returnPageDkghAcList('"+result+"')");
			break;
		case 12 :
			mWebView.loadUrl("javascript:returnPageDkbsList('"+result+"')");
			break;
		case 13 :
			mWebView.loadUrl("javascript:returnFindDkbsdj('"+result+"')");
			break;
		case 14 :
			mWebView.loadUrl("javascript:returnPageDkbsdjAcList('"+result+"')");
			break;
		case 15 :
			mWebView.loadUrl("javascript:returnGetCkkhjjhz('"+result+"')");
			break;
		case 16 :
			mWebView.loadUrl("javascript:returnGetJjJsHz('"+result+"')");
			break;
		case 17 :
			mWebView.loadUrl("javascript:returnGetJxgzhzmx('"+result+"')");
			break;
		case 18 :
			mWebView.loadUrl("javascript:returnGetDateByZH('"+result+"')");
			break;
		case 19 :
			mWebView.loadUrl("javascript:returnListBmByYhZh('"+result+"')");
			break;
		case 20 :
			mWebView.loadUrl("javascript:returnListYgByJg('"+result+"')");
			break;
		case 21 :
			mWebView.loadUrl("javascript:returnGetYwljjhz('"+result+"')");
			break;
		case 22 :
			mWebView.loadUrl("javascript:returnListYwljjjs('"+result+"')");
			break;
		case 23 :
			mWebView.loadUrl("javascript:returnGetTjDate('"+result+"')");
			break;
		case 24 :
			mWebView.loadUrl("javascript:returnPageLxList('"+result+"')");
			break;
		case 25 :
			mWebView.loadUrl("javascript:returnGetDkyxjjhz('"+result+"')");
			break;
		case 26 :
			mWebView.loadUrl("javascript:returnListDkyxjjjs('"+result+"')");
			break;
		case 27 :
			mWebView.loadUrl("javascript:returnGetDkghjjhz('"+result+"')");
			break;
		case 28 :
			mWebView.loadUrl("javascript:returnGetDkghJjJsHz('"+result+"')");
			break;
		case 29 :
			mWebView.loadUrl("javascript:returnGetDkbsndkh('"+result+"')");
			break;
		case 30 :
			mWebView.loadUrl("javascript:returnListDkbsjjmx('"+result+"')");
			break;
		case 31 :
			mWebView.loadUrl("javascript:returnGetDkbsyqkhhz('"+result+"')");
			break;
		case 32 :
			mWebView.loadUrl("javascript:returnListDkbsyqkhhzjjs('"+result+"')");
			break;
		case 33 :
			mWebView.loadUrl("javascript:returnGetDkbsyqdfhz('"+result+"')");
			break;
		case 34 :
			mWebView.loadUrl("javascript:returnListDkbsyqdfMx('"+result+"')");
			break;
		case 35 :
			mWebView.loadUrl("javascript:returnGetGljxgzjjhz('"+result+"')");
			break;
		case 36 :
			mWebView.loadUrl("javascript:returnGetBsyqdk('"+result+"')");
			break;
		case 37 :
			mWebView.loadUrl("javascript:returnGetYqdkbsnddqjs('"+result+"')");
			break;
		case 38 :
			mWebView.loadUrl("javascript:returnGetYqdkbsnddqjsjs('"+result+"')");
			break;
		case 39 :
			mWebView.loadUrl("javascript:returnGetGljxgzjjhzMx('"+result+"')");
			break;
		case 40 :
			mWebView.loadUrl("javascript:returnDzyhjjkhgzhz('"+result+"')");
			break;
		case 41 :
			mWebView.loadUrl("javascript:returnListDzyhjjjsMx('"+result+"')");
			break;
		case 42 :
			mWebView.loadUrl("javascript:returnGljxgzjjhzMx('"+result+"')");
			break;
		case 43 :
			mWebView.loadUrl("javascript:returnKhkkmx('"+result+"')");
			break;
		case 44 :
			mWebView.loadUrl("javascript:returnYfjxgzmx('"+result+"')");
			break;
		case 45 :
			mWebView.loadUrl("javascript:returnSgjjmx('"+result+"')");
			break;
		case 46 :
			mWebView.loadUrl("javascript:returnSaveHdtz('"+result+"')");
			break;
		case 47 :
			mWebView.loadUrl("javascript:returnHdtzList('"+result+"')");
			break;
		case 48 :
			mWebView.loadUrl("javascript:returnSaveQxtz('"+result+"')");
			break;
		case 49 :
			mWebView.loadUrl("javascript:returnGetHdtz('"+result+"')");
			break;
		case 50 :
			mWebView.loadUrl("javascript:returnGetHdmc('"+result+"')");
			break;
		case 51 :
			mWebView.loadUrl("javascript:returnSaveSbkcj('"+result+"')");
			break;
		case 52 :
			mWebView.loadUrl("javascript:returnPageSbkcjxxList('"+result+"')");
			break;
		}
	}    

	/**
	 * 调用页面javascript
	 * @param mothed
	 */
	private void callJavaScript(String type, String json){
		String mothed = "";
		if (type.equals(AppUtil.SHARE_DATA_ZJLX_ZDYX)) 
			mothed = "returnZjlx('"+json+"')";
		if (type.equals(AppUtil.SHARE_DATA_YXZL)) 
			mothed = "returnYxzl('"+json+"')";
		if (type.equals("bm")) 
			mothed = "returnBm('"+json+"')";
		if (type.equals("yh")) 
			mothed = "returnYh('"+json+"')";
		if (type.equals(AppUtil.SHARE_DATA_KHLB)) 
			mothed = "returnKhlb('"+json+"')";
		if (type.equals(AppUtil.SHARE_DATA_ZDYX)) 
			mothed = "returnZdyx('"+json+"')";

		final String javascript = mothed;

		mHandler.post(new Runnable() {
			public void run() {
				mWebView.loadUrl("javascript:" + javascript);
			}
		});
	}



	@Override
	public void callbacb() {
		isClose = false;
	}

}
